package cn.anecansaitin.whimsy.common.enchantment;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.register.ModEnchantments;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.item.BowItem;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.enchantment.Enchantment;
import net.minecraft.world.item.enchantment.EnchantmentCategory;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.Mod;
import net.neoforged.neoforge.event.entity.living.LivingEntityUseItemEvent;

/**
 * 扳机，在弓蓄力完成后自动射击
 */
@Mod.EventBusSubscriber(modid = Whimsy.MODID)
public class AutomaticTrigger extends Enchantment {
    public AutomaticTrigger() {
        super(Rarity.VERY_RARE, EnchantmentCategory.BOW, new EquipmentSlot[]{EquipmentSlot.MAINHAND});
    }

    @Override
    public boolean isTreasureOnly() {
        return true;
    }

    @Override
    public boolean isTradeable() {
        return false;
    }

    @Override
    public boolean isDiscoverable() {
        return false;
    }

    @SubscribeEvent
    public static void onBowTick(LivingEntityUseItemEvent.Tick event) {
        ItemStack bow = event.getItem();

        if (!(bow.getItem() instanceof BowItem)) {
            return;
        }

        AutomaticTrigger automaticTrigger = ModEnchantments.AUTOMATIC_TRIGGER.get();
        int level = bow.getEnchantmentLevel(automaticTrigger);

        if (level < automaticTrigger.getMinLevel()) {
            return;
        }

        if (bow.getItem().getUseDuration(bow) - event.getDuration() >= 20) {
            event.setCanceled(true);
            LivingEntity entity = event.getEntity();
            bow.releaseUsing(entity.level(), entity, 0);
        }
    }
}
